package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements ApUnlikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 不喜欢文章行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult noLike(UnLikesBehaviorDto dto) {
        //判断参数 type 文章id
        if (dto == null || dto.getArticleId() == null || (!dto.getType().equals((short) 0) && !dto.getType().equals((short) 1))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userID = AppThreadLocalUtils.getUser().getId();
        //根据id或者设备id查询出来行为实体 为null的话 返回
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(userID, dto.getEquipmentId());
        if (entry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"没有行为实体");
        }
        //根据实体和文章id去查询不喜欢行为表 如果没有 新增
        ApUnlikesBehavior unlike = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getEntryId, entry.getId())
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));
        if (unlike==null){
            ApUnlikesBehavior newUnlike = new ApUnlikesBehavior();
            newUnlike.setArticleId(dto.getArticleId());
            newUnlike.setCreatedTime(new Date());
            newUnlike.setEntryId(entry.getId());
            newUnlike.setType(dto.getType());
            save(newUnlike);
        }else {
            //如果有 修改
            unlike.setType(dto.getType());
            updateById(unlike);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
